package com.relax.mybatis.encrypt.interceptor;

import java.sql.Statement;
import java.util.Properties;

import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;

import com.relax.mybatis.encrypt.config.EncryptProperties;
import com.relax.mybatis.encrypt.util.EncryptUtil;

/**
 * @author relax
 * @date 2022/07/05
 * @desc 解密拦截器
 */
@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
public class DecryptInterceptor implements Interceptor {

    private EncryptProperties encryptProperties;

    public DecryptInterceptor(EncryptProperties encryptProperties) {
        this.encryptProperties = encryptProperties;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        return EncryptUtil.handleResultSet(invocation, (metaObject, fieldSetProperty) -> EncryptUtil
                .doDecrypt(this.encryptProperties, metaObject, fieldSetProperty));
    }

    public Object plugin(Object o) {
        return (o instanceof ResultSetHandler) ? Plugin.wrap(o, this) : o;
    }

    public void setProperties(Properties properties) {
        // do nothing
    }
}
